<template>
  <div class="cadre-com-details-box">
    <!-- <el-page-header @back="goBack" content="个人信息">fadfas</el-page-header> -->
    <header class="page-header">
      <div class="back" @click="goBack">
        <i class="el-icon-back">返回</i>
      </div>
      <div class="title-t">个人档案</div>
      <div class="btn-box" v-if="isEdit">
        <!-- <el-button type="primary">模版</el-button> -->
        <el-button type="primary" v-if="detailsStatus === '1'" @click="submitForm('short')">暂存</el-button>
        <el-button type="primary" v-if="detailsStatus === '1'" @click="submitForm('approve')">提交审批</el-button>
        <el-button type="primary" v-if="detailsStatus === '0'" @click="submitForm('duty')">提交上岗申请</el-button>
        <!-- <el-button type="primary">发起离岗申请</el-button> -->
      </div>
    </header>
    <div class="info-content">
      <div class="content">
        <el-form :model="informationalForm" label-width="100px" ref="informational-form-ref">
          <template>
            <div class="head">
              <div class="t">个人信息</div>
            </div>
            <el-row :gutter="20" style="z-index: 20;">
              <el-col :span="7">
                <el-form-item label="姓名" prop="personalName"
                  :rules="[{ required: detailsStatus !== '1', message: '请填写姓名', trigger: 'blur' }]">
                  <el-input :disabled="detailsStatus === '1'" v-model="informationalForm.personalName"
                    v-if="isEdit"></el-input>
                  <template v-else>{{ informationalForm.personalName }}</template>
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item label="性别" prop="sex">
                  <template v-if="isEdit">
                    <el-radio v-model="informationalForm.sex" :disabled="detailsStatus === '1'" label="1">女</el-radio>
                    <el-radio v-model="informationalForm.sex" :disabled="detailsStatus === '1'" label="0">男</el-radio>
                  </template>
                  <template v-else>{{ sexDist[informationalForm.sex] }}</template>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="民族" prop="nation"
                  :rules="[{ required: detailsStatus !== '1', message: '请选择民族', trigger: 'change' }]">
                  <el-select v-model="informationalForm.nation" :disabled="detailsStatus === '1'" v-if="isEdit">
                    <el-option v-for="v in $store.state.distObj.sz_staff_nation" :key="v.value" :value="v.value"
                      :label="v.label"></el-option>
                  </el-select>
                  <template v-else>{{ getValueContent($store.state.distObj.sz_staff_nation, informationalForm.nation)
                    }}</template>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="" prop="avatar" label-width="0">
                  <!-- <el-input v-model="form.avatar" placeholder="请输入头像地址" /> -->
                  <imageUpload :limit="1" v-model="informationalForm.avatar" v-if="isEdit && detailsStatus === '0'" />
                  <img v-else :src="imgUrlHead + informationalForm.avatar" class="avatar">
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="10">
                <el-form-item label="籍贯" prop="nativePlace"
                  :rules="[{ required: detailsStatus !== '1', message: '请填写籍贯', trigger: 'blur' }]">
                  <el-input v-model="informationalForm.nativePlace" :disabled="detailsStatus === '1'"
                    v-if="isEdit"></el-input>
                  <template v-else>{{informationalForm.nativePlace }}</template>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="出生地" prop="birthplace"
                  :rules="[{ required: detailsStatus !== '1', message: '请填写出生地', trigger: 'blur' }]">
                  <el-input v-model="informationalForm.birthplace" :disabled="detailsStatus === '1'"
                    v-if="isEdit"></el-input>
                  <template v-else>{{ informationalForm.birthplace }}</template>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="10">
                <el-form-item label="身份证号" prop="idNumber"
                  :rules="[{ required: detailsStatus !== '1', message: '请填写身份证号', trigger: 'blur' }, { validator: validatorIdNumber, trigger: 'blur'}]">
                  <el-input v-model="informationalForm.idNumber" :disabled="detailsStatus === '1'"
                    v-if="isEdit"></el-input>
                  <template v-else>{{ informationalForm.idNumber }}</template>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="出生日期" prop="birthday"
                  :rules="[{ required: detailsStatus !== '1', message: '请选择出生日期', trigger: 'change' }]">
                  <el-date-picker v-model="informationalForm.birthday" type="date" :disabled="detailsStatus === '1'"
                    value-format="yyyy-MM-dd" v-if="isEdit" placeholder="选择日期">
                  </el-date-picker>
                  <template v-else>{{ informationalForm.birthday }}</template>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="16">
                <el-form-item label="家庭地址" prop="familyAddress"
                  :rules="[{ required: detailsStatus !== '1', message: '请填写家庭地址', trigger: 'blur' }]">
                  <el-input v-model="informationalForm.familyAddress" :disabled="detailsStatus === '1'"
                    v-if="isEdit"></el-input>
                  <template v-else>{{ informationalForm.familyAddress }}</template>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="手机号码" prop="phone"
                  :rules="[{ required: detailsStatus !== '1', message: '请填写手机号码', trigger: 'blur' }, { validator: validatorPhone, trigger: 'blur'}]">
                  <el-input v-model="informationalForm.phone" :disabled="detailsStatus === '1'"
                    v-if="isEdit"></el-input>
                  <template v-else>{{ informationalForm.phone }}</template>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="政治面貌" prop="politicalStatus"
                  :rules="[{ required: detailsStatus !== '1', message: '请选择政治面貌', trigger: 'change' }]">
                  <el-select :disabled="detailsStatus === '1'" v-model="informationalForm.politicalStatus"
                    v-if="isEdit">
                    <el-option v-for="v in $store.state.distObj.sz_staff_political" :key="v.value" :value="v.value"
                      :label="v.label"></el-option>
                  </el-select>
                  <template v-else>{{ getValueContent($store.state.distObj.sz_staff_political,
                    informationalForm.politicalStatus) }}</template>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="参加工作时间" label-width="120px" prop="workYears"
                  :rules="[{ required: detailsStatus !== '1', message: '请选择参加工作时间', trigger: 'change' }]">
                  <el-date-picker v-model="informationalForm.workYears" value-format="yyyy-MM-dd" type="date"
                    :disabled="detailsStatus === '1'" v-if="isEdit" placeholder="选择日期">
                  </el-date-picker>
                  <template v-else>{{ informationalForm.workYears }}</template>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="参加机要工作时间" label-width="160px" prop="sensitiveWorkYears"
                  :rules="[{ required: detailsStatus !== '1', message: '请选择参加机要工作时间', trigger: 'change' }]">
                  <el-date-picker v-model="informationalForm.sensitiveWorkYears" value-format="yyyy-MM-dd" type="date"
                    :disabled="detailsStatus === '1'" v-if="isEdit" placeholder="选择日期">
                  </el-date-picker>
                  <template v-else>{{ informationalForm.sensitiveWorkYears }}</template>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="离岗原因">
                  <el-input></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="调离去向">
                  <el-input></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="离岗日期">
                  <el-date-picker
                    type="date"
                    placeholder="选择日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="脱密期">
                  <el-input></el-input>
                </el-form-item>
              </el-col>
            </el-row> -->
          </template>
        </el-form>
        <el-form :model="szPersonalRecordForm" label-width="100px" ref="szPersonal-record-form-ref">
          <template v-if="detailsStatus === '1'">
            <div class="head">
              <div class="t">在岗信息</div>
            </div>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="所属单位" prop="unit"
                  :rules="[{ required: true, message: '请填写所属单位', trigger: 'blur' }]">
                  <!-- <el-input v-model="szPersonalRecordForm.unit" v-if="isEdit"></el-input> -->
                  <el-cascader v-if="isEdit" :options="$store.state.passwordOptions"
                    :props="{'value': 'orgId', 'label': 'label'}" v-model="szPersonalRecordForm.unit"></el-cascader>
                  <template v-else>{{ szPersonalRecordForm.unitName }}</template>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="现任职务" prop="currentPosition"
                  :rules="[{ required: true, message: '请填写现任职务', trigger: 'blur' }]">
                  <el-input v-model="szPersonalRecordForm.currentPosition" v-if="isEdit"></el-input>
                  <template v-else>{{ szPersonalRecordForm.currentPosition }}</template>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="任职时间" prop="employmentDate"
                  :rules="[{ required: true, message: '请填写任职时间', trigger: 'change' }]">
                  <el-date-picker v-model="szPersonalRecordForm.employmentDate" value-format="yyyy-MM-dd" type="date"
                    v-if="isEdit" placeholder="选择日期">
                  </el-date-picker>
                  <template v-else>{{ szPersonalRecordForm.employmentDate }}</template>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="岗位名称" prop="jobTitle"
                  :rules="[{ required: true, message: '请选择岗位名称', trigger: 'change' }]">
                  <el-select v-model="szPersonalRecordForm.jobTitle" v-if="isEdit">
                    <el-option v-for="v in $store.state.distObj.sz_common_duty" :key="v.value" :value="v.value"
                      :label="v.label"></el-option>
                  </el-select>
                  <template v-else>{{ getValueContent($store.state.distObj.sz_common_duty,
                    szPersonalRecordForm.jobTitle) }}</template>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="涉密等级" prop="securityLevel"
                  :rules="[{ required: true, message: '请选择涉密等级', trigger: 'change' }]">
                  <el-select v-model="szPersonalRecordForm.securityLevel" v-if="isEdit">
                    <el-option v-for="v in $store.state.distObj.sz_classify_grade" :key="v.value" :value="v.value"
                      :label="v.label"></el-option>
                  </el-select>
                  <template v-else>{{ getValueContent($store.state.distObj.sz_classify_grade,
                    szPersonalRecordForm.securityLevel) }}</template>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="上岗时间" prop="onJobDate"
                  :rules="[{ required: true, message: '请选择上岗时间', trigger: 'change' }]">
                  <el-date-picker v-model="szPersonalRecordForm.onJobDate" value-format="yyyy-MM-dd" type="date"
                    v-if="isEdit" placeholder="选择日期">
                  </el-date-picker>
                  <template v-else>{{ szPersonalRecordForm.onJobDate }}</template>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="人员状态" prop="personnelStatus"
                  :rules="[{ required: true, message: '请选择人员状态', trigger: 'change' }]">
                  <el-select v-model="szPersonalRecordForm.personnelStatus" v-if="isEdit">
                    <el-option v-for="v in $store.state.distObj.sz_staff_status" :key="v.value" :value="v.value"
                      :label="v.label"></el-option>
                  </el-select>
                  <template v-else>{{ getValueContent($store.state.distObj.sz_staff_status,
                    szPersonalRecordForm.personnelStatus) }}</template>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="培训方式" prop="trainMethod"
                  :rules="[{ required: true, message: '请选择培训方式', trigger: 'change' }]">
                  <el-select v-model="szPersonalRecordForm.trainMethod" v-if="isEdit">
                    <el-option v-for="v in trainMethodOptins" :key="v.value" :value="v.value"
                      :label="v.label"></el-option>
                  </el-select>
                  <template v-else>{{ getValueContent(trainMethodOptins, szPersonalRecordForm.trainMethod)}}</template>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="指纹">
                  <el-button type="primary" :loading="fingLoading" @click="fingerprintEnter"
                    v-model="szPersonalRecordForm.fingerprintStatus" v-if="isEdit">录入</el-button>
                  <template v-if="szPersonalRecordForm.fingerprintStatus === '1'">已录入</template>
                  <template v-else> 未录入</template>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="人脸">
                  <el-button type="primary" v-model="szPersonalRecordForm.faceStatus" v-if="isEdit">录入</el-button>
                  已录入
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="取件卡">
                  <el-button type="primary" v-model="szPersonalRecordForm.cardStatus" v-if="isEdit">录入</el-button>
                  已录入
                </el-form-item>
              </el-col>
              <el-col :span="8"></el-col>
            </el-row>
          </template>
          <!-- <template>
            <div class="head">
              <div class="t">工作交接</div>
            </div>
            <el-table :data="tableList">
              <el-table-column prop="date" label="权限"></el-table-column>
              <el-table-column prop="data3" label="交接前">
                <el-input></el-input>
              </el-table-column>
              <el-table-column prop="data3" label="交接后">
                <el-input></el-input>
              </el-table-column>
            </el-table>
          </template>
          <template>
            <div class="head">
              <div class="t">其他权限</div>
            </div>
            <el-row>
              <el-col :span="6">
                <el-form-item label="指纹数据">
                  已录入
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="人脸数据">
                  已录入
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="指纹">
                  已录入
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-button type="primary">一键清除</el-button>
              </el-col>
            </el-row>
          </template>
          <template>
          <div class="head">工作经历</div>
          <el-table :data="tableList">
            <el-table-column prop="date" label="起止时间">
              <el-date-picker
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-table-column>
            <el-table-column prop="data1" label="在何地何部门">
              <el-input></el-input>
            </el-table-column>
            <el-table-column prop="data2" label="任何职">
              <el-input></el-input>
            </el-table-column>
            <el-table-column prop="data3" label="证明人">
              <el-input></el-input>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="scope"></el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="head">家庭成员</div>
          <el-table :data="tableList">
            <el-table-column prop="data1" label="关系">
              <el-input></el-input>
            </el-table-column>
            <el-table-column prop="data1" label="姓名">
              <el-input></el-input>
            </el-table-column>
            <el-table-column prop="data1" label="出生日期">
              <el-date-picker
                type="date"
                placeholder="选择日期">
              </el-date-picker>
            </el-table-column>
            <el-table-column prop="data1" label="政治面貌">
              <el-select>
                <el-option v-for="v in stepOptinons" :key="v.value" :value="v.value" :label="v.label"></el-option>
              </el-select>
            </el-table-column>
            <el-table-column prop="data1" label="工作单位及职务">
              <el-input></el-input>
            </el-table-column>
            <el-table-column prop="data1" label="通信地址">
              <el-input></el-input>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="scope"></el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="head">社会关系</div>
          <el-table :data="tableList">
            <el-table-column prop="data1" label="关系">
              <el-input></el-input>
            </el-table-column>
            <el-table-column prop="data1" label="姓名">
              <el-input></el-input>
            </el-table-column>
            <el-table-column prop="data1" label="出生日期">
              <el-date-picker
                type="date"
                placeholder="选择日期">
              </el-date-picker>
            </el-table-column>
            <el-table-column prop="data1" label="政治面貌">
              <el-select>
                <el-option v-for="v in stepOptinons" :key="v.value" :value="v.value" :label="v.label"></el-option>
              </el-select>
            </el-table-column>
            <el-table-column prop="data1" label="工作单位及职务">
              <el-input></el-input>
            </el-table-column>
            <el-table-column prop="data1" label="通信地址">
              <el-input></el-input>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="scope"></el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="head">教育经历</div>
          <el-table :data="tableList">
            <el-table-column prop="date" label="起止时间">
              <el-date-picker
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-table-column>
            <el-table-column prop="data3" label="学校名称">
              <el-input></el-input>
            </el-table-column>
            <el-table-column prop="data3" label="专业">
              <el-input></el-input>
            </el-table-column>
            <el-table-column prop="data3" label="学历">
              <el-input></el-input>
            </el-table-column>
            <el-table-column prop="data3" label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="scope"></el-button>
              </template>
            </el-table-column>
          </el-table>
          </template> -->
        </el-form>
      </div>
      <div class="side">
        <div class="annex-box" v-if="detailsStatus === '0'">
          <header>
            <div class="t">附件管理</div>
            <el-upload ref="upload" :limit="5" multiple v-if="isEdit" accept=".xlsx, .xls" :headers="upload.headers"
              :file-list="fileList" :action="upload.url" :disabled="upload.isUploading"
              :on-progress="handleFileUploadProgress"
              :on-success="(response, file, fileList) => { handleFileSuccess(response, file, fileList, 'leader') }"
              :on-exceed="(file, list) => { handleExceed(file, list, fileList, 5) }" :show-file-list="false"
              :before-upload="(file) => { beforeAvatarUpload(file, fileList, 5) }" :auto-upload="true">
              <el-button size="mini" type="text" icon="el-icon-upload2">上传文件</el-button>
            </el-upload>
          </header>
          <div class="con">
            <ul class="file-list" v-if="fileList.length > 0">
              <li v-for="(f, i) in fileList" :key="i">
                <i class="el-icon-document"></i>
                <span class="over" @click="downloadFile(f)">{{ f.name }}</span>
                <template v-if="isEdit"><i @click="deleteFile(fileList, i)" class="el-icon-circle-close"></i><i
                    class="el-icon-circle-check"></i></template>
              </li>
            </ul>
            <template v-else>
              <el-empty v-if="isEdit" :image-size="49" description="选择上传文件"></el-empty>
              <el-empty v-else :image-size="49" description="暂无文件"></el-empty>
            </template>
          </div>
        </div>
        <template v-if="detailsStatus === '1'">
          <div class="annex-box">
            <header>
              <div class="t">附件管理</div>
            </header>
            <div class="con">
              <el-table :data="dutyFileList">
                <el-table-column label="类型" prop="name" width="80"></el-table-column>
                <el-table-column label="文件" prop="fileName">
                  <template slot-scope="scope">
                    <div class="over" :title="scope.row.fileName">
                      <span @click="downloadFile(scope.row)">{{ scope.row.fileName }}</span>
                      <i @click="deleteFileListItem(dutyFileList, scope.$index)" v-if="scope.row.fileName && isEdit"
                        class="el-icon-delete"></i>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="操作" v-if="isEdit">
                  <template slot-scope="scope">
                    <el-button v-if="scope.$index === 0" @click="personalGenerate" type="text"
                      size="mini">生成</el-button>
                    <el-upload ref="upload" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
                      :disabled="upload.isUploading" :on-progress="handleFileUploadProgress"
                      :on-success="(response, file, fileList) => { handleFileSuccess(response, file, fileList, scope.row) }"
                      :on-exceed="handleExceed" :show-file-list="false" :auto-upload="true">
                      <el-button size="mini" type="text">上传</el-button>
                    </el-upload>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <!-- <div class="annex-box">
            <header>
              <div class="t">资格证书</div>
              <el-upload
                ref="upload" 
                :limit="10" 
                multiple
                accept=".xlsx, .xls"
                :headers="upload.headers"
                :action="upload.url"
                :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress" 
                :on-success="(response, file, fileList) => { handleFileSuccess(response, file, fileList, 'leader') }" 
                :on-exceed="handleExceed"
                :show-file-list="false"
                :auto-upload="true">
                <el-button size="mini" type="text" icon="el-icon-upload2">上传文件</el-button>
              </el-upload>
            </header>
            <div class="con">
              <ul class="file-list" v-if="fileList.length > 0">
                <li v-for="(f, i) in fileList" :key="i">
                  <i class="el-icon-document"></i> 
                  <span class="over" @click="downloadFile(f)">{{ f.name }}</span> 
                  <template v-if="isEdit"><i @click="deleteFile(fileList, i)" class="el-icon-circle-close"></i><i class="el-icon-circle-check"></i></template>
                </li>
              </ul>
              <template v-else>
                <el-empty v-if="isEdit" :image-size="49" description="选择上传文件"></el-empty>
                <el-empty v-else :image-size="49" description="暂无文件"></el-empty>
              </template>
            </div>
          </div> -->
          <div class="annex-box">
            <header>
              <div class="t">本单位培训材料</div>
              <el-upload ref="upload" multiple v-if="isEdit" accept=".xlsx, .xls" :headers="upload.headers" :limit="10"
                :file-list="trainFileList" :action="upload.url" :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress"
                :on-success="(response, file, fileList) => { handleFileSuccess(response, file, fileList, 'train') }"
                :before-upload="(file) => { beforeAvatarUpload(file, trainFileList, 10) }"
                :on-exceed="(file, list) => { handleExceed(file, list, trainFileList, 10) }" :show-file-list="false"
                :auto-upload="true">
                <el-button size="mini" type="text" icon="el-icon-upload2">上传文件</el-button>
              </el-upload>
            </header>
            <div class="con">
              <ul class="file-list" v-if="trainFileList.length > 0">
                <li v-for="(f, i) in trainFileList" :key="i">
                  <i class="el-icon-document"></i>
                  <span class="over" @click="downloadFile(f)">{{ f.name }}</span>
                  <template v-if="isEdit"><i @click="deleteFile(trainFileList, i)" class="el-icon-circle-close"></i><i
                      class="el-icon-circle-check"></i></template>
                </li>
              </ul>
              <template v-else>
                <el-empty v-if="isEdit" :image-size="49" description="选择上传文件"></el-empty>
                <el-empty v-else :image-size="49" description="暂无文件"></el-empty>
              </template>
            </div>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>
<script>
import { addPersonal, personalGenerate, personalId, personalUpdateRecord } from '@/api/cadre/cadre'
import { organDeptTree } from '@/api/cadre/leader'
import { getToken } from "@/utils/auth"
import { getDistContent } from "@/utils/index"
let websocket = null
export default {
  name: 'cadre-details',
  data() {
    return {
      orgId: '1721424754840653825',
      informationalForm: {
        personalId: '',
        deptId: '',
        personalName: '',
        sex: '1',
        nation: '',
        nativePlace: '',
        birthplace: '',
        idNumber: '',
        familyAddress: '',
        phone: '',
        birthday: '',
        politicalStatus: '',
        workYears: '',
        sensitiveWorkYears: '',
        avatar: '',
        delFlag: '',
        status: '',
        // szPersonalRecord: {
        //   unit: '',
        //   currentPosition: '',
        //   employmentDate: '',
        //   securityLevel: '',
        //   jobTitle: '',
        //   personnelStatus: '',
        //   trainMethod: '',
        //   onJobDate: '',
        //   fingerprintStatus: '',
        //   faceStatus: '',
        //   cardStatus: '',
        //   index: ''
        // },
        szPersonalFileList: []
      },
      szPersonalRecordForm: {
        unit: [],
        currentPosition: '',
        employmentDate: '',
        securityLevel: '',
        jobTitle: '',
        personnelStatus: '',
        trainMethod: '',
        onJobDate: '',
        fingerprintStatus: '',
        faceStatus: '',
        cardStatus: '',
        index: ''
      },
      imageUrl: '',
      fileList: [],
      trainMethodOptins: [
        { value: '0', label: '省厅统一培训' },
        { value: '1', label: '本机单位培训' }
      ],
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload"
      },
      imgUrlHead: process.env.VUE_APP_BASE_API,
      isEdit: false,
      detailsStatus: '',
      dutyFileList: [
        {name: '个人登记表', fileName: '', fileContent: '', fileType: 1},
        {name: '政审表', fileName: '', fileContent: '', fileType: 2},
        {name: '资格认定表', fileName: '', fileContent: '', fileType: 3},
        {name: '上岗申请表', fileName: '', fileContent: '', fileType: 4},
        {name: '责任书', fileName: '', fileContent: '', fileType: 5},
        {name: '其他材料', fileName: '', fileContent: '', fileType: 6}
      ],
      trainFileList: [],
      sexDist: {
        '0': '男',
        '1': '女'
      },
      fingLoading: false,
      passwordOptions: []
      //-----------------------------------------------------------------------------------------------
    }
  },
  created() {
    // console.log(this.$store.state.distObj)
    // console.log(this.$route.query)
    // if (!this.$store.state.passwordOptions){
    //   this.organDeptTree()
    // }
    this.isEdit = this.$route.query.isEdit === 'true'
    this.detailsStatus = this.$route.query.status
    if (this.$route.query.id) {
      if (!this.$store.state.passwordOptions) {
        this.organDeptTree()
      } else {
        this.personalId()
      }
    }
  },
  methods: {
    // 获取机构树
    organDeptTree() {
      let params = {
        objuid: this.orgId
      }
      organDeptTree(params).then(res => {
        if (res.code === 200) {
          this.$store.state.passwordOptions = res.data
          this.personalId()
        }
      })
    },
    getValueContent(list, val) {
      return getDistContent(list, val)
    },
    goBack() {
      // this.$router.go(-1)
      this.$router.push({
        name: 'Index',
        query: {
          cadresActive: this.$route.query.cadresActive
        },
        params: {
          activeName: '2'
        }
      })
    },
    validatorIdNumber(rule, value, callback) {
      if (this.detailsStatus === '1') {
        return
      }
      const IDCard_RGEX = /(^\d{15})|(^\d{17}(x|X|\d))/
      if (value === '') {
        callback(new Error('请填写身份证号'))
      } else if (!IDCard_RGEX.test(value)) {
        callback(new Error('请正确输入身份证号码'))
      } else {
        callback()
      }
    },
    validatorPhone(rule, value, callback) {
      if (this.detailsStatus === '1') {
        return
      }
      const PHONE_RGEX = /^1[34578]\d{9}$/
      if (value === '') {
        callback(new Error('请填写手机号'))
      } else if (!PHONE_RGEX.test(value)) {
        callback(new Error('请正确输入手机号码'))
      } else {
        callback()
      }
    },
    addPersonal() {
      let data = {...this.informationalForm}
      data.status = this.detailsStatus
      delete data.szPersonalRecord
      // 附件管理
      this.fileList.forEach(v => {
        let file = {
          fileName: v.response ? v.response.newFileName : v.fileName,
          fileContent: v.response ? v.response.fileName : v.fileContent,
          fileType: 0
        }
        data.szPersonalFileList.push(file)
      })
      addPersonal(data).then(res => {
        if (res.code === 200) {
          this.$message.success(res.msg)
          this.detailsStatus = '1'
          this.$router.push({
            name: 'Details',
            query: {
              status: '1',
              isEdit: 'true',
              id: res.data.personalId,
              cadresActive: '0'
            }
          })
          this.personalId()
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    personalUpdateRecord(type) {
      let data = {
        personalId: this.informationalForm.personalId,
        szPersonalRecord: this.szPersonalRecordForm,
        szPersonalFileList: [],
        status: type === 'approve' ? '1' : '0'
      }
      if (this.szPersonalRecordForm.unit && this.szPersonalRecordForm.unit.length > 0) {
        data.szPersonalRecord.unit = this.szPersonalRecordForm.unit[this.szPersonalRecordForm.unit.length - 1]
      }
      // return
      // 本单位培训资料
      this.trainFileList.forEach(v => {
        let file = {
          fileName: v.response ? v.response.newFileName : v.fileName,
          fileContent: v.response ? v.response.fileName : v.fileContent,
          fileType: 7
        }
        data.szPersonalFileList.push(file)
      })
      // 附件管理
      this.dutyFileList.forEach(v => {
        if (v.fileName) {
          data.szPersonalFileList.push(v)
        }
      })
      personalUpdateRecord(data).then(res => {
        if (res.code === 200) {
          this.$message.success(res.msg)
          if (type === 'approve') {
            this.$router.push({
              name: 'Cadre',
              query: {
                cadresActive: this.$route.query.cadresActive
              },
              params: {
                activeName: '2'
              }
            })
          }
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 生成个人登记表
    personalGenerate() {
      this.$download.fileDownload('/sz/personal/generate/' + this.$route.query.id, '个人登记表.docx')
    },
    getArrayValue(list, val, num, arr) {
      // console.log()
      for (let v of list) {
        if (v.children && v.children.length > 0) {
          arr[num] = v.orgId
          return this.getArrayValue(v.children, val, 1, arr)
        }
        if (v.orgId === val) {
          arr[num] = v.orgId
          return arr
        }
      }
    },
    personalId() {
      personalId(this.$route.query.id).then(res=>{
        if (res.code === 200) {
          // console.log(res)
          this.informationalForm = res.data
          this.szPersonalRecordForm = res.data.szPersonalRecord || {}
          let arr = []
          this.szPersonalRecordForm.unit = this.getArrayValue(this.$store.state.passwordOptions, this.szPersonalRecordForm.unit, 0, arr)
          this.fileList = []
          this.trainFileList = []
          res.data.szPersonalFileList && res.data.szPersonalFileList.forEach(v => {
            switch(v.fileType) {
              case '0':
                v.name = v.fileName
                this.fileList.push(v)
                break
              case '1':
              case '2':
              case '3':
              case '4':
              case '5':
              case '6':
                this.dutyFileList[v.fileType - 1].fileName = v.fileName
                this.dutyFileList[v.fileType - 1].fileContent = v.fileContent
                break
              case '7':
                v.name = v.fileName
                this.trainFileList.push(v)
                break
            }
          })
          
          // if (this.$refs['szPersonal-record-form-ref']){
            this.$nextTick(() => {
              this.$refs['szPersonal-record-form-ref'].clearValidate()
            })
          // }
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    handleAvatarSuccess() {},
    beforeAvatarUpload(file, fileList, num) {
      // if (fileList.length >= num) {
      //   this.$message.error('已成功上传10个文件，继续上传新文件将会按照顺序逐个替换最早上传的文件')
      // }
    },
    handlePreview() {},
    handleRemove() {},
    beforeRemove() {},
    handleExceed(files, list, fileList, num) {
      // this.$message.warning(`当前限制选择 ${num} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      this.$message.warning(`最多可上传${num}个文件`)
    },
    deleteFileListItem(list, index) {
      list[index].fileName = ''
      list[index].fileContent = ''
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    deleteFile(fileList, index) {
      this.$confirm(`确定移除 ${ fileList[index].name }？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        fileList.splice(index, 1)
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {})
    },
    downloadFile(file) {
      this.$download.resource(file.fileContent)
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList, type) {
      this.upload.isUploading = false;
      // 人员文件类型（0:档案材料，1:个人登记表，2:政审表，3:资格认证表，4:上岗申请表，5:责任书，6:其他材料，7:本单位培训资料，8:资格证书，9:年度政审），新增一个年度政审
      if(type === 'leader') {
        // this.fileList = [...this.fileList,...fileList]
        // this.fileList.push(file)
        this.fileList = fileList
        // this.fileList = this.fileList.splice(-5)
      } else if (type === 'train') {
        // this.trainFileList = [...this.trainFileList, ...fileList]
        // this.trainFileList.push(file)
        this.trainFileList = fileList
        // this.trainFileList = this.trainFileList.splice(-10)
      } else {
        switch (type.fileType) {
          case 1:
            this.dutyFileList[0].fileName = response.newFileName
            this.dutyFileList[0].fileContent = response.fileName
            break
          case 2:
            this.dutyFileList[1].fileName = response.newFileName
            this.dutyFileList[1].fileContent = response.fileName
            break
          case 3:
            this.dutyFileList[2].fileName = response.newFileName
            this.dutyFileList[2].fileContent = response.fileName
            break
          case 4:
            this.dutyFileList[3].fileName = response.newFileName
            this.dutyFileList[3].fileContent = response.fileName
            break
          case 5:
            this.dutyFileList[4].fileName = response.newFileName
            this.dutyFileList[4].fileContent = response.fileName
            break
          case 6:
            this.dutyFileList[5].fileName = response.newFileName
            this.dutyFileList[5].fileContent = response.fileName
            break
        }
      }
      this.$message.success('上传成功')
    },
    // 提交表单
    submitForm(type) {
      // this.informationalForm
      // console.log('type:', type)
      if (type === 'duty') {
        this.$refs['informational-form-ref'].validate((valid) => {
          if (valid) {
              this.addPersonal()
          } else {
            return false
          }
        })
      } else {
        if (type === 'short'){
          this.personalUpdateRecord(type)
        } else {
          if (this.szPersonalRecordForm.trainMethod === '1' && this.trainFileList.length === 0) {
            this.$message.error('请上传本单位培训材料')
            return
          }
          this.$refs['szPersonal-record-form-ref'].validate((valid) => {
            if (valid) {
              this.personalUpdateRecord(type)
            } else {
              return false
            }
          })
        }
      }
    },
    fingerprintEnter() {
      // console.log('websocket:', websocket)
      let registFinger = {
        "cmd": "registFinger",
        "param": {
          "fingerId": '001' || this.$route.query.id
        }
      }

      let stopRegister = {
        cmd: "stopRegister"
      }

      let close = {
        "cmd": "close",
        "param": {}
      }
      let open = {
        cmd: 'open',
        param: {
          deviceName: 'maisi',
          userName: 'USB',
          password: '00000000'
        }
      }
      // if (websocket) {
      //   websocket.send(JSON.stringify(open))
      // } else {
      websocket = new WebSocket('ws://127.0.0.1:7748/FingerPrint');
      // }
      websocket.onopen = function (evt) {
        console.log('onopen:', evt)
      }
      websocket.onclose = function (evt) {
        console.log('onclose:', evt)
      }
      websocket.onmessage = (evt) => {
        console.log('onmessage:', JSON.parse(evt.data))
        let data = JSON.parse(evt.data)
        if (data.code === 0 && data.name === 'Connect') {
          websocket.send(JSON.stringify(open))
        }
        if (data.code === 1015 && data.name === 'open') {
          this.fingLoading = false
          this.$message.warning(data.message, ',请链接指纹仪后重试')
          // websocket.send(JSON.stringify(registFinger))
        }
        if (data.code === 0 && data.name === 'open') {
          this.fingLoading = true
          websocket.send(JSON.stringify(registFinger))
        }
        if (data.code === 0 && data.name === 'registFinger') {
          this.$message.success(data.message)
        }
        if (data.code === 0 && data.name === 'pressFingerTimes') {
          this.$message.success(`指纹录入第 ${data.times} 次成功`)
        }
        if (data.code === 0 && data.name === 'registFingerRet') {
          if (data.data && data.data.retCode === '-1') {
            this.$message.error(data.data.retMsg)
          } else {
            this.szPersonalRecordForm.fingerprintStatus = '1'
            this.$message.success('指纹录入:' + data.message)
          }
          this.fingLoading = false
          websocket.send(JSON.stringify(stopRegister))
        }
        if (data.code === 0 && data.name === 'stopRegister') {
          this.fingLoading = false
          websocket.send(JSON.stringify(close))
        }
      }
      websocket.onerror = function (evt) {
        console.log('onerror:', evt)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.cadre-com-details-box{
  padding: 20px;
  background: #fafafa;
  .page-header{
    margin-bottom: 24px;
    box-shadow: 0 0 4px rgba(74, 91, 107, 0.16);
    border-radius: 4px;
    display: flex;
    line-height: 32px;
    padding: 10px 20px;
    background: #fff;
    .back{
      cursor: pointer;
      .el-icon-back::before{
        margin-right: 6px;
      }
      font-size: 14px;
      padding-right: 16px;
    }
    .title-t{
      padding-left: 16px;
      flex: 1;
      position: relative;
    }
    .title-t::before{
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      width: 1px;
      height: 20px;
      background: #dcdfe6;
      transform: translateY(-50%);
    }
  }
  .el-date-editor{
    width: 100%;
  }
  .info-content{
    display: flex;
    .content{
      border-radius: 4px;
      flex: 1;
      background: #fff;
      box-shadow: 0 0 4px rgba(74, 91, 107, 0.16);
      padding:0 20px 20px;
      .head{
        border-bottom: solid 2px rgba(220, 223, 230, .5);
        margin: 20px 0;
        line-height: 30px;
        .t{
          position: relative;
          display: inline-block;
          padding: 0 4px;
        }
        .t::before {
          content: '';
          position: absolute;
          left: 0;
          bottom: -2px;
          width: 100%;
          border-bottom:solid 2px #409eff;
        }
      }
    }
    .side{
      min-width: 260px;
      max-width: 260px;
      margin-left: 20px;
      .annex-box{
        background: #fff;
        margin-bottom: 20px;
        border-radius: 4px;
        box-shadow: 0 0 4px rgba(74, 91, 107, 0.16);
        header{
          line-height: 30px;
          font-size: 14px;
          padding: 4px 16px;
          border-bottom: solid 1px rgba(220, 223, 230, .5);
          display: flex;
          .t{
            flex: 1;
          }
        }
        .con{
          padding: 8px;
        }
        .el-table{
          .over{
            display: flex;
            line-height: 32px;
            align-items: center;
            span {
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              flex: 1;
              color: #409eff;
            }
            i{
              cursor: pointer;
            }
          }
        }
        .file-list{
          height: 93px;
          overflow-y: auto;
          li {
            color: #606266;
            margin-top: 5px;
            border-radius: 4px;
            line-height: 26px;
            transition: .5s;
            padding: 0 6px;
            cursor: pointer;
            display: flex;
            align-items: center;
            span{
              flex: 1;
              padding: 0 4px;
            }
            .over{
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              color: #409eff;
            }
            .el-icon-circle-check{
              color: #67c23a;
            }
            .el-icon-circle-close{
              color: #f56c6c;
              display: none;
            }
          }
          li:hover{
            background: #F5F7FA;
            .el-icon-circle-close{
              display: block;
            }
            .el-icon-circle-check{
              display: none;
            }
          }
        }
        .el-empty{
          padding: 0;
        }
      }
    }
  }
}
</style>
<style lang="scss">
.cadre-com-details-box{
  .component-upload-image{
    position: absolute;
    right: 0;
    top: 0;
    .el-upload__tip{
      display: none;
    }
  }
  .component-upload-image .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .component-upload-image .el-upload:hover {
    border-color: #409EFF;
  }
  .el-upload--picture-card {
    font-size: 18px;
    color: #8c939d;
    width: 132px;
    height: 132px;
    line-height: 132px;
    text-align: center;
  }
  .el-upload-list--picture-card .el-upload-list__item{
    width: 132px;
    height: 132px;
  }
  .avatar {
    position: absolute;
    right: 0;
    top: 0;
    width: 132px;
    height: 132px;
    display: block;
  }
}
</style>